<?php

namespace App\Trip\Train\Seat;

use Illuminate\Support\Facades\Cache;

class SeatInventory implements Interfaces\SeatInventoryInterface
{

    private string $cache_key;
    private string $seat_name;
    private string $to_station_code;
    private string $from_station_code;
    private string $train_code;

    /**
     * @param string $train_code 车次
     * @param string $from_station_code 出发站
     * @param string $to_station_code 目的站
     * @param string $seat_name 坐席名称
     */
    public function __construct(string $train_code,
                                string $from_station_code,
                                string $to_station_code,
                                string $seat_name)
    {
        $this->train_code        = $train_code;
        $this->from_station_code = $from_station_code;
        $this->to_station_code   = $to_station_code;
        $this->seat_name         = $seat_name;
        $this->cache_key         = "Train:SeatInventory:{$train_code}:{$from_station_code}:{$to_station_code}:$seat_name";
    }


    public function getInventory(): int
    {
        return Cache::get($this->cache_key) ?: 0;
    }

    /**
     * 更新库存  查询触发更新.下单成功后异步触发更新
     *
     * @param int $inventory
     *
     * @return void
     */
    public function setInventory(int $inventory): void
    {
        Cache::put($this->cache_key, $inventory, 5 * config('trip.ttl.minutes'));
    }
}